#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <ctype.h>

/*
*   @author Joseph Conrad Stack
 *          jcstack
 *          directory.c
 * 
 *  this file provides methods to use with the global directory
 */ 

void initDir();
void ls();
int add(char name[],int index);
int rm(char name[]);

/*
*   file type direct   
 * @param index     index value of file
 * @param name      name of file
 */ 
struct direct {
    int index;
    char entry[12];
};


/*
*   @param fileDir  a global array of type "direct"
 */ 
struct direct fileDir[32];

/*
*   initDir method sets all indexes in directory to 0
 *  @param i    used to parse directory
 */ 
void initDir(){
    int i=0;
    for(i=0;i<32;i++){
        fileDir[i].index = 0;
    }
}


/*
*   ls method prints out the files in the directory
 *  @param i    used to parse directory
 */
void ls(){
    int i=0;
    for(i=0;i<32;i++){
        if((fileDir[i].index)!=0){
            printf("%d %s\n",fileDir[i].index, fileDir[i].entry);
        }
    }
}


/*
*   method add looks to see if a file of aspecified name can be added to
 *  the list, if possible, then it is done
 *  @param i        used to parse directory
 *  @param space    used to check for an empty slot
 *  @return         returns 0 if the string could be added, -1 if it could not
 */ 
int add(char name[],int index){
    int i=0;
    int space=-1;
    if(strlen(name) > 11){
        return -1;
    }
        for(i=0;i<strlen(name);i++){
            if(!isalnum(name[i])){
                if(name[i] != '.' & name[i] != ',' & name[i] != '_'){
                    return -1;
                }
            }
        }
        
    for(i=0;i<32;i++){
        if(strcmp(name,fileDir[i].entry) ==0){
            return -1;
        }
        if(fileDir[i].index == 0){
            space = i;
        }
    }
    if(space == -1){
        return -1;
    }
    else{
        fileDir[space].index = index;
        strcpy(fileDir[space].entry, name);
        return 0;
    }
    
 }




/*
*   rm method used to rm a entry from the list
 *  @param i        used to parse through the directory
 *  @param name     the name to be removed
 *  @return         return 0 if a file was removed, -1 if a file was not removed
 */ 
int rm(char name[]){
    int i = 0;
    for(i=0;i<32;i++){
        if(strcmp(name,fileDir[i].entry) ==0){
            fileDir[i].index = 0;
            /* fileDir[i].entry = NULL;     you would have to add this line, or files of the same name couldn't be added after one was rm()ed */
            return 0;
        }
    }
    return -1;
    
}
